package com.glhtgyxy.biyesheji.Controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

@Controller
@RequestMapping("upload")
@CrossOrigin(origins = "*")
public class uploadController {

    @PostMapping("/image")
    public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
        System.out.println("上传照片处理中："+file);

        if (!file.isEmpty()) {
            try {
                // 指定保存文件的路径，这里假设是D盘下的img文件夹
                String filePath = "D:/image/" + file.getOriginalFilename();
                String originalFilename = file.getOriginalFilename();
                int lastIndex = originalFilename.lastIndexOf('.');
                String fileNameWithoutExtension = originalFilename.substring(0, lastIndex);

                merchantController.imgname.add(fileNameWithoutExtension);
                // 创建文件输出流
                FileOutputStream fileOutputStream = new FileOutputStream(filePath);
                // 将上传的文件写入到指定路径
                fileOutputStream.write(file.getBytes());
                fileOutputStream.close();
                System.out.println("上传照片处理结束，文件名:"+fileNameWithoutExtension);

                return ResponseEntity.ok("File uploaded successfully!");
            } catch (IOException e) {
                e.printStackTrace();
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to upload file!");
            }
        } else {
            return ResponseEntity.badRequest().body("File is empty!");
        }
    }
}
